import Vue from 'vue'
import Vuex from 'vuex'

// 安装插件
Vue.use(Vuex)

// module
const moduleA = {
    state: {
        name: "zhang san"
    },
    mutations: {
        updateName(state, payload) {
            state.name = payload
        }
    },
    actions: {
        asyncUpdateName(context, payload){
            setTimeout(() => {
                context.commit('updateName', payload)
            }, 1000)
        }
    }, 
    getters: {
        getFullName(state) {
            return state.name
        },
        getFullName1(state, getters) {
            return getters.getFullName + '-1'
        }, 
        getFullName2(state, getters, rootState) {
            return getters.getFullName1 + rootState.counter
        }
    },
}

// 创建对象 store
const store = new Vuex.Store({
    state: {
        counter: 1000,
        todos: [
            {id: "1", name: "A", done: true},
            {id: "2", name: "B", done: false},
            {id: "3", name: "C", done: true}
        ],
        info: {name: "Li Hua", age: 20, address: "da, st 5"},
    },
    mutations: {
        // 方法
        increment(state) {
            state.counter++
        },
        decrement(state){
            state.counter--
        },
        addTodo(state, stu) {
            state.todos.push(stu);
        },
        changeInfo(state) {
            Vue.set(state.info, "address", "rd 2, ud")
            Vue.delete(state.info, "name")
            // setTimeout(() => {
            //     Vue.set(state.info, "address", "rd 2, ud")
            //     Vue.delete(state.info, "name")
            // }, 1000)
        }
    },
    actions: {// 异步操作
        updateInfo(context, payload) {
            return new Promise((resolve, reject) => {
                setTimeout(() => {
                    context.commit("changeInfo");
                    console.log(payload);
                    resolve('actions: updateInfo里面完成了');
                }, 1000);
                
            })
        }
    },
    getters: {
        todoTools(state){
           return state.todos.filter(todo => todo.done);
        },
        doneLength(state, getters) {
            return getters.todoTools.length
        }
    },
    modules: {
        a: moduleA
    }
})

// 导出store
export default store